import pool from '../config/database';
export interface UserInfo {
  userId: string;
  headImg: string;
  workUrl: string;
  motto: string;
  birthDay: string;
  sex: string;
  hobby: string;
  ortherInfo?: string;
  created_at?: string;
  updated_at?: string;
}
export class UserInfoModel {
  async create(userInfo: UserInfo): Promise<any> {
    const created_at = new Date().toLocaleString();
    const updated_at = new Date().toLocaleString();
    const [res] = await pool.execute(
      'INSERT INTO userInfo (userId, headImg, workUrl, motto, birthDay, sex, hobby, ortherInfo, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [userInfo.userId, userInfo.headImg, userInfo.workUrl, userInfo.motto, userInfo.birthDay, userInfo.sex, userInfo.hobby, userInfo.ortherInfo, created_at, updated_at]
    )
    return res;
  }
  async findByUserId(userId: string): Promise<UserInfo | null> {
    const [rows] = await pool.execute(
      'SELECT * FROM userInfo WHERE userId = ?',
      [userId]
    );
    const userInfo = rows as UserInfo[];
    return userInfo[0] || null;
  }
  async updateUserInfo(userInfo: { userId: string, headImg: string, workUrl: string, motto: string, birthDay: string, sex: string, hobby: string, ortherInfo?: string }) {
    const updated_at = new Date().toLocaleString();
    const [res] = await pool.execute(
      'UPDATE userInfo SET headImg = ?, workUrl = ?, motto = ?, birthDay = ?, sex = ?, hobby = ?, ortherInfo = ?, updated_at = ? WHERE userId = ?',
      [userInfo.headImg, userInfo.workUrl, userInfo.motto, userInfo.birthDay, userInfo.sex, userInfo.hobby, userInfo.ortherInfo, updated_at, userInfo.userId]
    )
    return res;
  }
  async getPageInfo(page: number, pageSize: number): Promise<any> {
    const [rows] = await pool.execute(
      `SELECT userId, headImg, workUrl, motto, birthDay, sex, hobby FROM userInfo ORDER BY created_at DESC LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}`
    );
    const [totalRows] = await pool.execute(
      'SELECT COUNT(*) AS total FROM userInfo'
    );
    const userInfos = rows as UserInfo[];
    return {
      rows: userInfos,
      total: (totalRows as any)[0].total
    };
  }
}